package cn.dylan.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Date;


public class RequestTimeFilter implements GatewayFilter, Ordered {

    private static final Logger log=LoggerFactory.getLogger(RequestTimeFilter.class);

    /**
     * exchange上下文
     * GatewayFilterChain gateway filter调用链对象
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        // 获取请求路径
        String path = request.getURI().getPath();
        exchange.getAttributes().put("startTime",new Date().getTime());

        // 执行之后
        return chain.filter(exchange).then(
                Mono.fromRunnable(() -> {
                    // 开始时间
                    Long startTime = exchange.getAttribute("startTime");
                    // 结束时间
                    Long endTime = (System.currentTimeMillis() - startTime);
                    // 打印当前请求耗时
                    log.info(exchange.getRequest().getURI().getRawPath() + ": " + endTime + "ms");
                })
        );


    }

    @Override
    public int getOrder() {
        return 0;
    }
}
